// pages/home/productSearch/productSearch.js
const request = require("../../../utils/network.js")
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    imgBase: app.imgBase,
    historyKeys: [],
    search_text: "",
    products: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getHistoryKeysList();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  /* 设置搜索值 */
  getSearch_text:function(e){
    this.setData({
      search_text: e.detail.value
    })
  },
  /* 清空搜索值 */
  clearSearchText(){
    this.setData({
      search_text: ""
    });
  },
  /* 搜索 */
  searchInfo(){
    var that = this;
    var cmd = this.data.search_text.trim();
    if(cmd!=""){
      this.setHistoryKeysList(cmd);
      var url = '/goods/getSearchGoodsList';
      var parms = {
        name: cmd
      }
      request.request(url, parms, function (res) {
        that.setData({
          products: res.data,
        });
        that.getHistoryKeysList();
      }, function () {
        wx.showToast({
          title: '加载数据失败',
        })
      }, 'GET');
    }
  },
  /* 记录历史记录 */
  setHistoryKeysList(cmd){
    var historyKeys = wx.getStorageSync('historyKeys') || [];
    if(historyKeys.indexOf(cmd)==-1){
      var oldTemp = historyKeys.slice(0, 5);
      var newTemp = [cmd].concat(oldTemp);
      wx.setStorageSync('historyKeys', newTemp);
    }
  },
  /* 获取历史搜索记录 */
  getHistoryKeysList(){
    this.setData({
      historyKeys: (wx.getStorageSync('historyKeys') || []).map(key => {
        return key
      })
    });
  },
  /* 清空历史记录 */
  clearHistory(){
    var that = this;
    wx.showModal({
      title: '提示',
      content: '确认删除历史记录？',
      success: function (res) {
        if (res.confirm) {
          wx.setStorageSync('historyKeys', []);
          that.getHistoryKeysList();
        } 
      }
    })
  },
   /* 点击历史纪录关键字搜索 */
  searchHistoryKey(e) {
    this.setData({
      search_text: e.currentTarget.dataset.value
    })
    this.searchInfo();
  },
  /* 点击取消 */
  closeSearch(){
    wx.navigateBack({
      delta: 1
    })
  },
  watchDetail: function (event) {
    var that = this;
    var id = event.currentTarget.dataset.id;
    var url = '../productDetail/productDetail?id=' + id;
    wx.navigateTo({
      url: url
    })
  }
})